//
//  ImageCollectionView.m
//  HWSGW
//
//  Created by avachen on 15/11/9.
//  Copyright © 2015年 luxuanrui. All rights reserved.
//

#import "ImageCollectionView.h"

#import "Movie.h"

#import "UIViewExt.h"
@implementation ImageCollectionView





- (instancetype)initWithFrame:(CGRect)frame
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.minimumLineSpacing = 0;
    //    flowLayout.sectionInset = UIEdgeInsetsMake(<#CGFloat top#>, <#CGFloat left#>, <#CGFloat bottom#>, <#CGFloat right#>)
    self = [super initWithFrame:frame collectionViewLayout:flowLayout];
    if (self) {
        self.delegate = self;
        self.dataSource = self;
        
        self.showsHorizontalScrollIndicator = NO;
        self.showsVerticalScrollIndicator = NO;
        //设置scrollView减速的速度
        //范围（0-1）默认 0， 1
        self.decelerationRate = 0.5;
        
        //        self.pagingEnabled = YES;
        
        
    }
    //    self.contentInset = UIEdgeInsetsMake(0, 100, 0, 100);
    
    return self;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    CGFloat offsetX = (self.frame.size.width - _pageWidth) / 2;
    return UIEdgeInsetsMake(0, offsetX, 0, offsetX);
    
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(_pageWidth, self.frame.size.height);
}
/*
 velocity :加速度,手指离开页面时滑动得速度
 targetContentOffset:目标偏移量，减速停止之后
 
 */

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    //    NSLog(@"%f", velocity.x);
    //    NSLog(@"目标偏移量：%f", targetContentOffset->x);
    //    NSLog(@"当前的偏移量：%f", scrollView.contentOffset.x);
    //计算滑动停止之后，单元格位置的索引
    int index = (targetContentOffset->x + _pageWidth / 2) / _pageWidth;
    //    NSLog(@"index = %d", index);
    //设置下一页的偏移量
    targetContentOffset->x = index * _pageWidth;
    if (self.currentItem == index && index < self.data.count - 1) {
        //判断velocity滑动速度，速度快得话直接到下一页
        if (velocity.x > 0.3) {
            index++;
        }else if (velocity.x < -0.3 && index > 0){
            index--;
            
        }
        
    }
    //记录当前的显示页
    self.currentItem = index;
    
    
}
#pragma mark - UICollectionView delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.data.count;
}

@end
